package com.zou.jokes.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.zou.jokes.Constant;
import com.zou.jokes.R;
import com.zou.jokes.adapter.FavoriteAdapter;
import com.zou.jokes.beans.BaseDataEntity;
import com.zou.jokes.sqlite.MyDao;
import com.zou.jokes.utils.RxBus;
import com.zou.jokes.utils.UserEvent;

import java.util.List;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zou on 2016/6/6.
 */
public class MyFavoriteFragment extends Fragment {

    private List<BaseDataEntity> datas;
    private FavoriteAdapter      adapter;
    private MyDao                myDao;
    private Subscription         subscribe;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorite, container, false);
        myDao = new MyDao(getContext());

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rcv_f);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        Observable.just(myDao.getDatas())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(baseDataEntities -> {
                    datas = baseDataEntities;
                    adapter = new FavoriteAdapter(datas, getContext());
                    recyclerView.setAdapter(adapter);
                });
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        subscribe = RxBus.getDefault().toObserverable(UserEvent.class)
                .subscribe(userEvent -> {
                    if (userEvent.getId() == Constant.UPDATEFAV) {
                        update();
                    }
                });
    }

    private void update() {
        Observable.just(myDao.getDatas())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(baseDataEntities -> {
                    datas.clear();
                    datas.addAll(baseDataEntities);
                    adapter.notifyDataSetChanged();
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!subscribe.isUnsubscribed())
            subscribe.unsubscribe();
    }
}
